const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

class ShiftModel {
  /**
   * 获取所有班次信息
   * @returns {Promise<Object>} 当前班次和历史班次
   */
  async getAllShifts() {
    try {
      // 获取当前活跃班次
      const currentShift = await prisma.shift.findFirst({
        where: { status: 'active' },
        include: {
          cashier: {
            select: {
              id: true,
              name: true,
              username: true
            }
          },
          payments: {
            select: {
              id: true,
              orderId: true,
              method: true,
              amount: true,
              status: true,
              createdAt: true,
              updatedAt: true
            }
          },
          channelSales: {
            include: {
              channel: true
            }
          }
        }
      });

      // 获取历史班次（已结束的）
      const historyShifts = await prisma.shift.findMany({
        where: { status: 'ended' },
        orderBy: { endTime: 'desc' },
        include: {
          cashier: {
            select: {
              id: true,
              name: true,
              username: true
            }
          },
          payments: {
            select: {
              id: true,
              orderId: true,
              method: true,
              amount: true,
              status: true,
              createdAt: true,
              updatedAt: true
            }
          },
          channelSales: {
            include: {
              channel: true
            }
          }
        }
      });

      // 处理当前班次数据
      let formattedCurrentShift = null;
      if (currentShift) {
        const paymentMethods = {};
        currentShift.payments.forEach(payment => {
          paymentMethods[payment.paymentMethod] = payment.amount;
        });

        formattedCurrentShift = {
          id: currentShift.id,
          cashier: currentShift.cashier.name || currentShift.cashier.username,
          startTime: currentShift.startTime,
          orderCount: currentShift.orderCount,
          totalSales: currentShift.totalSales,
          averageOrder: currentShift.totalSales / (currentShift.orderCount || 1),
          paymentMethods
        };
      }

      // 处理历史班次数据
      const formattedHistoryShifts = historyShifts.map(shift => {
        const paymentMethods = {};
        shift.payments.forEach(payment => {
          paymentMethods[payment.paymentMethod] = payment.amount;
        });

        const channelSales = shift.channelSales.map(cs => ({
          id: cs.channel.id,
          name: cs.channel.name,
          amount: cs.amount
        }));

        return {
          id: shift.id,
          cashier: shift.cashier.name || shift.cashier.username,
          startTime: shift.startTime,
          endTime: shift.endTime,
          orderCount: shift.orderCount,
          totalSales: shift.totalSales,
          averageOrder: shift.totalSales / (shift.orderCount || 1),
          paymentMethods,
          channelSales,
          note: shift.note
        };
      });

      return {
        currentShift: formattedCurrentShift,
        historyShifts: formattedHistoryShifts
      };
    } catch (error) {
      console.error('获取班次信息失败:', error);
      throw error;
    }
  }

  /**
   * 获取当前班次信息
   * @param {number} id 班次ID
   * @returns {Promise<Object>} 当前班次信息
   */
  async getCurrentShift(id) {
    try {
      const shift = await prisma.shift.findUnique({
        where: { id: Number(id) },
        include: {
          cashier: {
            select: {
              id: true,
              name: true,
              username: true
            }
          },
          payments: true,
          orders: {
            select: {
              id: true,
              total: true
            }
          }
        }
      });

      if (!shift) {
        throw new Error('班次不存在');
      }

      // 更新订单数和销售额
      const orderCount = shift.orders.length;
      const totalSales = shift.orders.reduce((sum, order) => sum + order.total, 0);
      const averageOrder = orderCount > 0 ? totalSales / orderCount : 0;

      // 更新班次信息
      await prisma.shift.update({
        where: { id: Number(id) },
        data: {
          orderCount,
          totalSales,
          averageOrder
        }
      });

      // 构建支付方式数据
      const paymentMethods = {};
      shift.payments.forEach(payment => {
        paymentMethods[payment.paymentMethod] = payment.amount;
      });

      return {
        id: shift.id,
        cashier: shift.cashier.name || shift.cashier.username,
        startTime: shift.startTime,
        orderCount,
        totalSales,
        averageOrder,
        paymentMethods
      };
    } catch (error) {
      console.error('获取当前班次信息失败:', error);
      throw error;
    }
  }

  /**
   * 开始新班次
   * @param {Object} data 班次数据
   * @returns {Promise<Object>} 新班次信息
   */
  async startShift(data) {
    try {
      // 检查是否有活跃班次
      const activeShift = await prisma.shift.findFirst({
        where: { status: 'active' }
      });

      if (activeShift) {
        throw new Error('已有进行中的班次，请先结束当前班次');
      }

      // 创建新班次
      const newShift = await prisma.shift.create({
        data: {
          cashierId: data.userId,
          startTime: new Date(),
          status: 'active',
          // 初始化支付方式
          payments: {
            create: [
              { paymentMethod: 'cash', amount: 0, systemAmount: 0, actualAmount: 0 },
              { paymentMethod: 'wechat', amount: 0, systemAmount: 0, actualAmount: 0 },
              { paymentMethod: 'alipay', amount: 0, systemAmount: 0, actualAmount: 0 },
              { paymentMethod: 'complimentary', amount: 0, systemAmount: 0, actualAmount: 0 }
            ]
          }
        },
        include: {
          cashier: {
            select: {
              id: true,
              name: true,
              username: true
            }
          },
          payments: true
        }
      });

      // 构建支付方式数据
      const paymentMethods = {};
      newShift.payments.forEach(payment => {
        paymentMethods[payment.paymentMethod] = payment.amount;
      });

      return {
        id: newShift.id,
        cashier: newShift.cashier.name || newShift.cashier.username,
        startTime: newShift.startTime,
        orderCount: 0,
        totalSales: 0,
        averageOrder: 0,
        paymentMethods
      };
    } catch (error) {
      console.error('开始班次失败:', error);
      throw error;
    }
  }

  /**
   * 结束班次
   * @param {Object} data 结束班次数据
   * @returns {Promise<Object>} 结束的班次信息
   */
  async endShift(data) {
    try {
      const { shiftId, confirmAmounts, note } = data;

      // 获取班次信息
      const shift = await prisma.shift.findUnique({
        where: { id: Number(shiftId) },
        include: {
          cashier: {
            select: {
              id: true,
              name: true,
              username: true
            }
          },
          payments: true,
          orders: {
            select: {
              id: true,
              total: true,
              channelId: true
            },
            where: {
              createdAt: {
                gte: prisma.shift.findUnique({
                  where: { id: Number(shiftId) },
                  select: { startTime: true }
                }).startTime
              }
            }
          }
        }
      });

      if (!shift) {
        throw new Error('班次不存在');
      }

      if (shift.status !== 'active') {
        throw new Error('班次已结束');
      }

      // 更新订单数和销售额
      const orderCount = shift.orders.length;
      const totalSales = shift.orders.reduce((sum, order) => sum + order.total, 0);
      const averageOrder = orderCount > 0 ? totalSales / orderCount : 0;

      // 计算渠道销售数据
      const channelSales = {};
      shift.orders.forEach(order => {
        const channelId = order.channelId || 1; // 默认渠道ID为1
        if (!channelSales[channelId]) {
          channelSales[channelId] = 0;
        }
        channelSales[channelId] += order.total;
      });

      // 准备渠道销售数据
      const channelSalesData = Object.entries(channelSales).map(([channelId, amount]) => ({
        channelId: Number(channelId),
        amount
      }));

      // 更新支付方式数据
      const paymentUpdates = Object.entries(confirmAmounts).map(([method, amount]) => {
        const payment = shift.payments.find(p => p.paymentMethod === method);
        return prisma.shiftPayment.update({
          where: { id: payment.id },
          data: {
            actualAmount: parseFloat(amount),
            systemAmount: payment.amount,
            difference: payment.amount - parseFloat(amount)
          }
        });
      });

      // 结束班次
      const endedShift = await prisma.shift.update({
        where: { id: Number(shiftId) },
        data: {
          endTime: new Date(),
          status: 'ended',
          orderCount,
          totalSales,
          averageOrder,
          note,
          channelSales: {
            createMany: {
              data: channelSalesData
            }
          }
        },
        include: {
          cashier: {
            select: {
              id: true,
              name: true,
              username: true
            }
          },
          payments: true,
          channelSales: {
            include: {
              channel: true
            }
          }
        }
      });

      // 执行支付方式更新
      await Promise.all(paymentUpdates);

      // 获取更新后的支付方式
      const updatedPayments = await prisma.shiftPayment.findMany({
        where: { shiftId: Number(shiftId) }
      });

      // 构建支付方式数据
      const paymentMethods = {};
      updatedPayments.forEach(payment => {
        paymentMethods[payment.paymentMethod] = payment.actualAmount;
      });

      // 构建渠道销售数据
      const formattedChannelSales = endedShift.channelSales.map(cs => ({
        id: cs.channel.id,
        name: cs.channel.name,
        amount: cs.amount
      }));

      // 获取热销商品数据
      const topProducts = await this.getTopProductsForShift(shift.startTime, new Date());

      return {
        id: endedShift.id,
        cashier: endedShift.cashier.name || endedShift.cashier.username,
        startTime: endedShift.startTime,
        endTime: endedShift.endTime,
        orderCount,
        totalSales,
        averageOrder,
        paymentMethods,
        channelSales: formattedChannelSales,
        note: endedShift.note,
        topProducts
      };
    } catch (error) {
      console.error('结束班次失败:', error);
      throw error;
    }
  }

  /**
   * 获取班次期间的热销商品
   * @param {Date} startTime 开始时间
   * @param {Date} endTime 结束时间
   * @returns {Promise<Array>} 热销商品列表
   */
  async getTopProductsForShift(startTime, endTime) {
    try {
      // 获取订单项目
      const orderItems = await prisma.orderItem.findMany({
        where: {
          order: {
            createdAt: {
              gte: startTime,
              lte: endTime
            }
          }
        },
        include: {
          product: {
            select: {
              id: true,
              name: true
            }
          }
        }
      });

      // 统计商品销售情况
      const productStats = {};
      orderItems.forEach(item => {
        const productId = item.productId;
        if (!productStats[productId]) {
          productStats[productId] = {
            name: item.product.name,
            quantity: 0,
            amount: 0
          };
        }
        productStats[productId].quantity += item.quantity;
        productStats[productId].amount += item.price * item.quantity;
      });

      // 转换为数组并排序
      const topProducts = Object.values(productStats)
        .sort((a, b) => b.amount - a.amount)
        .slice(0, 10); // 取前10个

      return topProducts;
    } catch (error) {
      console.error('获取热销商品失败:', error);
      return []; // 返回空数组而不是抛出错误
    }
  }
}

module.exports = new ShiftModel(); 